import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store';
import NProgress from 'nprogress'; // nprogress 进度条
import 'nprogress/nprogress.css'; // nprogress 进度条样式
import { againLogin } from '@/utils/common'
Vue.use(VueRouter)

const router = new VueRouter({
  routes
})
// 路由多次点击报错
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch((error) => error)
}
/**
 * @description 全局前置守卫
 * @param {Object} to 即将要进入的目标
 * @param {Object} from 当前导航正要离开的路由
 * @param {function} next
 * */
router.beforeEach((to, from, next) => {
  NProgress.start(); // 初始化进度条
  if (to.fullPath === '/login') {
    next();
  }else {
    if (store.getters.token) {
      store.dispatch('base/watchRoute', to).then()
      next();
    }else{
      againLogin()
    }
  }

})
// 全局后置钩子
router.afterEach(() => {
  // 跳转完成，关闭进度条
  NProgress.done();
});
export default router
